package com.motu.monstercity.server.game.logic;

import com.googlecode.protobuf.format.JsonFormat;
import com.motu.monstercity.module.common.iap.IapGift;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.act.Act;
import com.motu.monstercity.server.game.commondata.act.ActDetail;
import com.motu.monstercity.server.game.commondata.act.DailyPass;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ActManager extends ActUserData {
    public static final Logger logger = LoggerFactory.getLogger(ActManager.class);

    /**
     * 检测是否有推送礼包活动
     */
    public static void checkActIapGiftPush(UserInfo userInfo, UserExtInfo userExtInfo) {
        List<UserIapGiftPush> userIapGiftPushList = null;
        ConcurrentHashMap<Long, Act> actMap = getActList();
        for (Act act : actMap.values()) {
            if (act.getType() != Act.ACT_TYPE_PUSH_GIFT) {
                continue;
            }
            if (!act.isStart(userInfo.getServerId())) {
                continue;
            }
            int[] params = act.getActParamArray();
            if (params == null || params.length <= 0) {
                continue;
            }
            if (userIapGiftPushList == null) {
                userIapGiftPushList = GameUser.getUserIapGiftPushList(userInfo.getId());
            }
            // 检测活动推送礼包是否触发
            GameIapManager.checkTriggerActIapGiftPush(userInfo, act, userExtInfo, Tool.intArrayToList(params),
                    userIapGiftPushList);
        }
    }

    public static void loadActInfo(Common.PBUserData.Builder pbUserData, UserInfo userInfo, UserExtInfo userExtInfo) {
        ConcurrentHashMap<Long, Act> actList = getActList();
        for (Act act : actList.values()) {
            if (!act.isShowtime(userInfo.getServerId()) || act.getIsShow() == 0) {
                continue;
            }
            Common.PBActInfo.Builder build = Common.PBActInfo.newBuilder();
            build.setId(act.getId());
            build.setType(act.getType());
            build.setName(act.getName());
//            build.setSort(act.getSort());
            build.setStime(act.getStartTime());
            build.setEtime(act.getEndTime());
            build.setShowtime(act.getShowTime());
            build.setClosetime(act.getCloseTime());
            build.setParam(act.getParam());
            build.setExtParam(act.getExtraParam());
//            build.setReplaceitem(act.getReplaceitem());
//            build.setDay(act.getDiffDays());
            pbUserData.getActBuilder().putActList(act.getId(), build.build());
        }
    }

    public static void loadUserActInfo(Common.PBUserData.Builder pbUserData, UserInfo userInfo, UserExtInfo userExtInfo) {
        long userId = userInfo.getId();
        List<UserAct> userActList = ActDaysManager.getUserMotifActList(userInfo, false);
        for (UserAct userAct : userActList) {
            ProtoDataUtils.updatePBUserData(pbUserData, userAct, true);
        }
        //下方新手注册七日领奖
        UserSign userSign = ActManager.getUserSign(userId);
        ProtoDataUtils.updatePBUserData(pbUserData, userSign, true);
        UserCommonAct userCommonAct = ActManager.getUserCommonAct(userId);
        updateHundredDraw(pbUserData, userCommonAct, userExtInfo, true);
    }

    /**
     * 获取当前新手主题的分组id
     */
    public static int getNewcomerMotifGroup(UserExtInfo userExtInfo) {
        int diffDay = TimeUtils.getDiffDay(userExtInfo.getRegisterTime()) + 1;
        if (diffDay <= AllParam.COMMON_THEME_KEEP_TIME * AllParam.COMMON_THEME_ACT_THEME_GROUP_ID.length) {
            for (int i = 0; i < AllParam.COMMON_THEME_ACT_THEME_GROUP_ID.length; i++) {
                int endDay = AllParam.COMMON_THEME_KEEP_TIME * (i + 1);
                if (diffDay <= endDay) {
                    return AllParam.COMMON_THEME_ACT_THEME_GROUP_ID[i];
                }
            }
        }
        return 0;
    }

    /**
     * 获取新一期的开始时间和结束时间
     */
    public static long[] getNewStartActTimeInfo(UserExtInfo userExtInfo) {
		long[] timeInfo = new long[2];
        int diffDay = TimeUtils.getDiffDay(userExtInfo.getRegisterTime()) + 1;
        if (diffDay <= AllParam.COMMON_THEME_KEEP_TIME * AllParam.COMMON_THEME_ACT_THEME_GROUP_ID.length) {
            int round = (diffDay - 1) / AllParam.COMMON_THEME_KEEP_TIME;
            long startTime = TimeUtils.getStartTimeOfDay(userExtInfo.getRegisterTime())
                    + AllParam.COMMON_THEME_KEEP_TIME * Tool.DAY * round;
            timeInfo[0] = startTime;
            timeInfo[1] = startTime + AllParam.COMMON_THEME_KEEP_TIME * Tool.DAY - 1;
        }
        return timeInfo;
    }

    public static void checkAllAct(UserInfo userInfo, UserExtInfo userExtInfo) {
        long curTime = TimeUtils.getCurTime();
        ConcurrentHashMap<Long, Act> actList = getActList();
        for (Act act : actList.values()) {
            if (act.getType() == Act.ACT_TYPE_MAINTAIN) {//维护补偿
                if (act.isStart(userInfo.getServerId(), curTime)) {
                    // 获取活动明细
                    ConcurrentHashMap<Long, ActDetail> actDetailList = act.getActDetailMap();
                    if (actDetailList == null) {
                        continue;
                    }
                    UserAct userAct = getUserAct(userInfo.getId(), act.getId());// 活动信息
                    if (userAct == null) {
                        userAct = new UserAct(userInfo.getId(), act.getId());
                        userAct.doCreate();
                    } else {
                        continue;
                    }

                    for (ActDetail actDetail : actDetailList.values()) {
                        //发送维护补偿 新建邮件
//                        String title = MailManager.makeWordIdString(MailConstant.MAIL_ID_TYPE_ACT_WORD, act.getNameWordId());
//                        String content = MailManager.makeWordIdString(MailConstant.MAIL_ID_TYPE_ACT_WORD, act.getDesWordId());
//                        MailManager.sendMail(userInfo.getId(),title,content, LogType.ACT_MAINTAIN,actDetail.getParamObj().getJsonArray("list").toString(), MailConstant.MAIL_TYPE_IMPORTANT);

                        int titleId = act.getNameWordId();
                        int contentId = act.getDesWordId();

                        List<RewardItem> rewardItems = MailManager.takeRewardItem(actDetail.getParamObj().getJsonArray("list").toString());
                        MailManager.sendActMail(userInfo.getId(),titleId, contentId, rewardItems, LogType.ACT_MAINTAIN);

                        break;
                    }
                }
            }
        }
    }

    public static void updateHundredDraw(Common.PBUserData.Builder pbUserData, UserCommonAct userCommonAct, UserExtInfo userExtInfo, boolean isInit) {
        if (isInit) {
            Common.PBActHundredDraw.Builder hundredDrawBuilder = userCommonAct.takeHundredDrawInitBuilder();
            hundredDrawBuilder.setHundredDrawDay(userExtInfo.getLoginDayCount());
            pbUserData.getOnceActBuilder().setHundredDraw(hundredDrawBuilder);
        } else {
            Common.PBActHundredDraw.Builder hundredDrawBuilder = userCommonAct.takeHundredDrawBuilder();
            pbUserData.getOnceActBuilder().setHundredDraw(hundredDrawBuilder);
        }
    }

    public static int[] getActTenDayGiftInfo(long registerTime) {
        if (registerTime < AllParam.ACT_TEN_DAY_GIFT_REGISTER_TIME) {
            return AllParam.ACT_TEN_DAY_GIFT;
        }
        return AllParam.ACT_TEN_DAY_GIFT2;
    }

    public static boolean checkHundredDrawRedPoint(UserInfo userInfo) {
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo, SystemConstant.SYSTEM_MODULE_ID_HUNDRED_DRAW)) {
            return false;
        }
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userInfo.getId());
        // 获取当前是登录的第几天
        int curLoginDay = userExtInfo.getLoginDayCount();
        int[] actTenDayGift = ActManager.getActTenDayGiftInfo(userExtInfo.getRegisterTime());
        if (actTenDayGift == null || actTenDayGift.length <= 0){
            return false;// 奖励未配置
        }
//        if (curLoginDay > actTenDayGift.length / 2) { // 超过100天不需要显示百抽
//            return false;
//        }
        UserCommonAct userCommonAct = ActManager.getUserCommonAct(userInfo.getId());
        for (int i = 1; i <= actTenDayGift.length / 2; i++){
            if (curLoginDay < i) {
                break;
            }
            if (!Tool.isInList(userCommonAct.getHundredDrawGetArray(), i)){
                return true;
            }
            if (Tool.isInList(userCommonAct.getHundredChargeArray(), i) && !Tool.isInList(userCommonAct.getChargeHundredDrawGetArray(), i)) {
                return true;
            }
        }
        return false;
    }

    public static boolean checkDailySignRedPoint(long userId) {
        UserDailySign userDailySign = ActManager.getUserDailySign(userId);
        if (!userDailySign.isReward()
                || (userDailySign.isCharge() && !userDailySign.isChargeReward())) {
            return true;
        }
        return false;
    }

    public static boolean checkRedPoint(UserInfo userInfo, CsGameSystem.CSGameSystemRedPointResponse.Builder builder) {
        boolean hasRedPoint = false;
        CsGameSystem.RedPoint_CommonAct.Builder redPoint = CsGameSystem.RedPoint_CommonAct.newBuilder();
        if (checkHundredDrawRedPoint(userInfo)) {
            hasRedPoint = true;
            redPoint.setIsHundredDraw(true);
        }
        long userId = userInfo.getId();
        // 每日签到小红点
        if (checkDailySignRedPoint(userId)) {
            hasRedPoint = true;
            redPoint.setIsDailySignReward(true);
        }
        if (checkDailySpecialOfferRedPoint(userInfo)) {
            hasRedPoint = true;
            redPoint.setIsDailySpecialOfferGift(true);
        }
        // 判断高级签到红点
        if(checkDailyPassRedPoint(userInfo)) {
            hasRedPoint = true;
            redPoint.setIsDailyPassReward(true);
        }
        if (hasRedPoint) {
            builder.setCommonAct(redPoint);
        }
//        System.out.println(JsonFormat.printToString(builder.build()));
        return hasRedPoint;
    }

    public static boolean checkDailySpecialOfferRedPoint(UserInfo userInfo) {
        if (!SystemManager.checkModuleOpen(userInfo, SystemConstant.SYSTEM_MODULE_ID_DAILY_OFFER_GIFT)) {
            return false;
        }
        List<IapGift> iapGiftList = IapManager.getIapGiftTypeList(IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER);
        if (iapGiftList != null && !iapGiftList.isEmpty()) {
            for (IapGift iapGift : iapGiftList) {
                UserIapGift userIapGift = IapManager.getUserIapGift(userInfo.getId(), iapGift.getId());
                // 免费礼包
                if (iapGift.getIapId() == 0){
                    if (userIapGift == null || userIapGift.getNum() < iapGift.getLimitNum()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    //  高级签到红点
    public static boolean checkDailyPassRedPoint(UserInfo userInfo) {
        long userId = userInfo.getId();
        if (!SystemManager.checkModuleOpen(userInfo, SystemConstant.SYSTEM_MODULE_ID_DAILY_PASS)) {
            return false;
        }
        UserDailyPass userDailyPass = ActManager.getUserDailyPass(userId);
        // 判断开始时间和结束时间是否到了
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        boolean checkDailyPassValid = ActManager.checkDailyPassValid(userDailyPass.getGroupId(), userExtInfo.getRegisterTime());
        if (!checkDailyPassValid) {return false;}
        // 判断是否有奖励可以领取
        DailyPass configByGroupId = getDailyPassConfigByGroupId(userDailyPass.getGroupId());
        if(configByGroupId == null) return false;
        // 判断今日是什么时候
        int diffDay = TimeUtils.getDiffDay(userExtInfo.getRegisterTime(), TimeUtils.getCurTime()) + 1;
        int startDay = diffDay - configByGroupId.getStartDay();
        boolean contains = userDailyPass.getSignListArray().contains(startDay);
        if (!contains) return true;

        // 判断是否有购买高级礼包,买了但是没有签到的话红点亮起
        UserIapGift userIapGift = IapManager.getUserIapGift(userInfo.getId(), configByGroupId.getIapId());
        if (userIapGift != null && userIapGift.getNum() > 0) {
            contains = userDailyPass.getSignList2Array().contains(startDay);
            if (!contains) return true;
        }
        return false;
    }


    /**
     * 检查是否能购买高级签到战令礼包
     * @param userInfo
     * @param iapGift
     * @return
     */
    public static ErrorWord checkBuyDailyPass(UserInfo userInfo, IapGift iapGift) {
        if (iapGift.getType() != IapGift.TYPE_ACT_DAILY_PASS) {
            return ErrorWord.INVALID_OPERATION;
        }
        // 是否没有解锁
        if (!SystemManager.checkModuleOpen(userInfo, SystemConstant.SYSTEM_MODULE_ID_DAILY_PASS)) {
            return ErrorWord.MODULE_LOCKED;
        }
        long userId = userInfo.getId();
        UserDailyPass userDailyPass = ActManager.getUserDailyPass(userId);
        // 判断开始时间和结束时间是否到了
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        boolean checkDailyPassValid = ActManager.checkDailyPassValid(userDailyPass.getGroupId(), userExtInfo.getRegisterTime());
        if (!checkDailyPassValid) { return ErrorWord.INVALID_OPERATION;}
        // 判断
        return null;
    }
}
